package de.dopichaj.labrador.inex;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Comparator;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.zip.GZIPInputStream;

import javax.xml.parsers.ParserConfigurationException;

import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.xml.sax.SAXException;

import de.dopichaj.labrador.search.hit.DocHitMap;
import de.dopichaj.labrador.search.hit.Hit;
import de.dopichaj.labrador.search.hit.HitHierarchyTree;
import de.dopichaj.labrador.search.merge.pattern.PatternMerge;
import de.dopichaj.labrador.search.prune.ContextPruner;
import de.dopichaj.labrador.search.prune.FuzzyLengthBasedPruner;
import de.dopichaj.labrador.search.prune.ResultTreePruner;


/**
 * Create context graphs (skyline diagrams) from intermediate results written by
 * DocHitMap.
 * 
 * Outputs a ploticus file with pic diagrams on System.out.
 */
public class DrawContextGraphs {
    
    private static final ResultTreePruner pruner = new ContextPruner(new PatternMerge());
    private static final ResultTreePruner lengthPruner = new FuzzyLengthBasedPruner();
    private static boolean printFuzzy = true;
    private static boolean printLength = true;
    private static boolean printHeader = false;
    private static ContextGraphWriter graph;

    public static void main(String[] args) throws ParserConfigurationException, SAXException {
        
        Options options = new Options();
        options.addOption("f", "omitFuzzyPruning", false, "omit fuzzy-pruned tree");
        options.addOption("l", "omitlengthPruning", false, "omit length-pruned tree");
        options.addOption("i", "infoHeader", false, "print informational header for each graph");
        options.addOption("w", "width", true, "width of diagram (in inches; default: 7)");
        options.addOption("h", "width", true, "height of diagram (in inches; default: 7)");
        CommandLineParser parser = new BasicParser();
        CommandLine cmd = null;
        try {
            cmd = parser.parse(options, args);
        } catch (ParseException pe) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("this", options);
            System.exit(1);
        }
        if (cmd.hasOption("f")) {
            printFuzzy = false;
        }
        if (cmd.hasOption("l")) {
            printLength = false;
        }
        if (cmd.hasOption("i")) {
            printHeader = true;
        }
        double width = Double.parseDouble(cmd.getOptionValue("w", "7"));
        double height = Double.parseDouble(cmd.getOptionValue("h", "7"));
        graph = new ContextGraphWriter(new PrintWriter(System.out));

        for (String name : cmd.getArgs()) {
            process(new File(name), width, height);
        }
        graph.close();
    }

    private static void process(File file, double width, double height) throws ParserConfigurationException, SAXException {
        try {
            if (file.isFile()) {
                InputStream in = null;
                try {
                    // try to open as gzip input stream
                    in = new GZIPInputStream(new FileInputStream(file));
                } catch (IOException e) {
                    // if we could open the FileInputStream, but not the GZIPInputStream,
                    // we hopefully have an uncompressed file
                    in = new FileInputStream(file);
                }
                
                DocHitMap results = new DocHitMap(in);
                SortedSet<HitHierarchyTree> sorted = new TreeSet<HitHierarchyTree>(
                    new Comparator<HitHierarchyTree>() {

                        public int compare(HitHierarchyTree o1, HitHierarchyTree o2) {
                            float s1 = o1.getRoot().getScore();
                            float s2 = o2.getRoot().getScore();
                            if (s1 > s2) {
                                return -1;
                            } else if (s1 < s2) {
                                return 1;
                            } else {
                                return o1.getRoot().getFile().compareTo(o2.getRoot().getFile());
                            }    
                        }
                    }
                ); 
                
                for (File doc : results.getDocs()) {
                    HitHierarchyTree tree = new HitHierarchyTree(results.getHitsFromDoc(doc));
                    sorted.add(tree);
                }
                
                for (HitHierarchyTree tree : sorted) {
                    if (tree.getRoot().getScore() > 0.0f) {
                        // find the maximum score
                        float maxScore = 0.0f;
                        for (Hit hit : tree.getAllHits()) {
                            if (hit.getScore() > maxScore) {
                                maxScore = hit.getScore();
                            }
                        }
                        String label = printHeader ? tree.getRoot().getFile().toString() : "";
                        maxScore = Math.round(maxScore + 0.5f);
                        graph.drawTree(tree, width, height, maxScore, label);
                        pruner.prune(tree);
                        if (printFuzzy) {
                            graph.drawTree(tree, width, height, maxScore, label);
                        }
                        lengthPruner.prune(tree);
                        if (printLength) {
                            graph.drawTree(tree, width, height, maxScore, label);
                        }
                    }
                }
                
            } else if (file.isDirectory()) {
                for (String subFile : file.list()) {
                    process(new File(file, subFile), width, height);
                }
            }
            
        } catch (IOException e) {
            System.err.println("Error on file " + file);
            e.printStackTrace();
        }
    }
}
/*
Copyright (c) 2007 Philipp Dopichaj

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
